package com.sgrape.packageinstaller;

import android.content.Context;
import android.os.Environment;

import java.io.*;
import java.util.UUID;

public final class FileUtil {
    public static void copyFile(File src, File des) throws IOException {
        FileInputStream fis = new FileInputStream(src);
        copyFile(fis, des);
    }

    public static void copyFile(InputStream in, File des) throws IOException {
        int len;
        byte[] buff = new byte[512];
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(des);
            while ((len = in.read(buff)) > 0) {
                fos.write(buff, 0, len);
                fos.flush();
            }
        } finally {
            try {
                if (in != null) in.close();
                if (fos != null) fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static File getCacheDir(Context context) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            return context.getExternalCacheDir();
        } else {
            return context.getCacheDir();
        }
    }

    public static File createTempApk(Context context) {
        String apkName = UUID.randomUUID().toString().replace("-", "") + ".apk";
        File file = new File(getCacheDir(context), apkName);
        if (file.getParentFile().exists()) file.getParentFile().mkdirs();
        return file;
    }
}
